<template>
    <view class="bg-[#f8f8f8] min-h-[100vh]" :style="themeColor()">
		<block v-if="saleOpen == 1 && !pageLoading">
			<view class="fixed w-full z-2  !bg-[#F6F6F6]">
				<view class="w-full overflow-hidden" :style="headerStyle">
					<!-- #ifdef MP-WEIXIN -->
					<top-tabbar :data="param" :scrollBool="topTabarObj.getScrollBool()" class="top-header"/>
					<!-- #endif -->
					<view class="card-template sidebar-marign mt-[312rpx]">
						<view class="flex justify-between items-baseline mb-[50rpx]">
							<view class="flex flex-col">
								<text class="text-[26rpx] h-[36rpx] leading-[36rpx] text-[#333] mb-[6rpx]">销售奖励（元）</text>
								<text class="text-[44rpx] price-font text-[#EF000C] min-h-[58rpx] leading-[58rpx]">{{moneyFormat(saleCommission.sale_commission)||0.00}}</text>
							</view>
							<view class="flex items-center h-[34rpx]" @click="applyCashOut">
								<text class="text-[24rpx] text-[#626779]">去提现</text>
								<text class="nc-iconfont nc-icon-youV6xx text-[22rpx] text-[#626779]"></text>
							</view>
						</view>
						<view class="flex item-center justify-between">
							<view class="flex flex-col w-[50%]">
								<text class="text-[24rpx] h-[34rpx] leading-[34rpx] text-[#8288A2] mb-[8rpx]">待发放（元）</text>
								<text class="text-[36rpx] min-h-[46rpx] leading-[46rpx] text-[#333] price-font">{{moneyFormat(saleCommission.wait_sale_commission)||0.00}}</text>
							</view>
							<view class="flex flex-col w-[50%]">
								<text class="text-[24rpx] h-[34rpx] leading-[34rpx] text-[#8288A2] mb-[8rpx]">已发放（元）</text>
								<text class="text-[36rpx] min-h-[46rpx] leading-[46rpx] text-[#333] price-font">{{moneyFormat(saleCommission.sale_commission_send)||0.00}}</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="tab-style-1 pb-[0] mt-[30rpx]">
					<scroll-view :scroll-x="true" scroll-with-animation :scroll-into-view="'id' + (subActive>3 ? subActive - 2 : 0)" class="!h-[100%] flex-1">
						<view class="tab-left">
							<view :id="'id' + index" class="tab-left-item pb-[20rpx]" :class="{ 'class-select': fromType === item.key,'ml-30rpx':index}" @click="fromTypeFn(item.key,index)" v-for="(item, index) in typeList">{{ item.name }}</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<mescroll-body ref="mescrollRef" :down="{ use: false }" @init="mescrollInit" @up="getSaleMemberFn" :top="mescrollTop">
				<block v-if="info.length && !infoLoading && !loading">
					<view v-for="(item,index) in info" :keys="index" class="flex flex-col px-[20rpx] py-[22rpx] rounded-[16rpx] bg-[#fff] mt-[24rpx] sidebar-marign" @click="toDetail(item.period_id)">
						<view class="flex items-center justify-between h-[40rpx]">
							<view v-if="item.is_settlement" class="text-[#333] text-[28rpx] flex items-center">
								<text class="text-[24rpx] mr-[6rpx]">结算时间</text>
								<text>{{item.sale_end_time}}</text>
							</view>
							<view v-else class="text-[#333] text-[28rpx] flex items-center">
								<text class="text-[24rpx] mr-[6rpx]">预计结算时间</text>
								<text>{{item.sale_end_time}}</text>
							</view>
							<view class="text-[32rpx] font-600 text-[#333]">
								+{{moneyFormat(item.reward_money)}}
							</view>	
						</view>
						<view class="flex items-center justify-between mt-[10rpx] h-[34rpx]">
							<view class="text-[24rpx] text-[#8288A2]">销售金额：{{item.order_money}}</view>
							<view class="rounded-[8rpx] px-[10rpx] py-[6rpx] text-[20rpx]" :class="{'bg-[#FFF5F6] text-[#EF000C]': item.is_send, 'bg-[#ECF4FF] text-[#308AFF]': !item.is_send}">
								{{item.is_send?'已发放':'待发放'}}
							</view>
						</view>
					</view>
				</block>
				<view class="box-border pt-[20rpx] px-[30rpx]  body-bottom" :style="{'height':'calc(100vh - 20rpx - '+mescrollTop +')'}" v-if="!info.length && !infoLoading && !loading">
					<view class="h-full rounded-[16rpx] flex items-center justify-center">
						<mescroll-empty :option="{'icon': img('addon/shop_fenxiao/sale/empty.png'), 'tip': '暂无销售奖励记录', 'btnText': '去逛逛'}" @emptyclick="redirect({ url: '/addon/shop_fenxiao/pages/goods' })"></mescroll-empty>
					</view>
				</view>
			</mescroll-body>
		</block>
		<view class="h-[100vh] w-[100vw] flex justify-center items-center" v-if="saleOpen == 0 && !pageLoading">
			<!-- #ifdef MP-WEIXIN -->
			<top-tabbar :data="param" :scrollBool="topTabarObj.getScrollBool()" class="top-header"/>
			<!-- #endif -->
            <u-empty text="销售奖励设置未开启" width="347rpx" height="265rpx" :icon="img('static/resource/images/system/empty.png')"/>
        </view>
        <u-loading-page bg-color="rgb(248,248,248)" :loading="pageLoading" loadingText="" fontSize="16" color="#333"></u-loading-page>

    </view>
</template>
<script lang="ts" setup>
import { t } from '@/locale'
import { ref, computed } from 'vue'
import { img, redirect, moneyFormat,pxToRpx } from '@/utils/common';
import { getSaleMemberList,getSaleMemberNowList,getSaleMemberCommission,getSaleConfig } from '@/addon/shop_fenxiao/api/sale'
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onPageScroll, onReachBottom, onLoad } from '@dcloudio/uni-app';
import { topTabar } from '@/utils/topTabbar'

// 获取系统状态栏的高度
let menuButtonInfo:any = {};
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let param = topTabarObj.setTopTabbarParam({title:'销售奖励'})
/********* 自定义头部 - end ***********/

/********* 头部样式 - start ***********/
const headerStyle = computed(()=>{
	let obj:any = {
		backgroundImage: 'url(' + img('addon/shop_fenxiao/sale/head_bg.png') + ') ',
		backgroundSize: 'contain',
		backgroundRepeat: 'no-repeat'
	}
	// #ifdef H5
	obj.backgroundPositionY = '-170rpx';
	// #endif
	return obj
})
const mescrollTop = computed(()=>{
	if(Object.keys(menuButtonInfo).length){
		// pxToRpx(8) => 表示胶囊的padding-bottom  690 => 表示列表以上的该高度【不包括自定义头部】
		return (pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + pxToRpx(8) + 690)+'rpx'
	}else{
		// 表示列表以上的高度
		return '690rpx'
	}
})

/********* 头部样式 - end ***********/
/********* 是否开启销售奖励设置 - start ***********/
let saleOpen = ref<any>('');
let pageLoading = ref<boolean>(true);
onLoad(async ()=>{
	await getSaleConfig().then(res =>{
        saleOpen.value = res.data.is_open
		if(saleOpen.value == 0){
			param = topTabarObj.setTopTabbarParam({title:'销售奖励',topStatusBar:{textColor:'#333',bgColor:'#fff'}})
		}
		pageLoading.value = false;
    })
})
/********* 是否开启销售奖励设置  - end ***********/

/************ 类型筛选-start ************/ 
const typeList = ref([
	{name:'全部',key:'all'},
	{name:'待发放',key:'0'},
	{name:'已发放',key:'1'}
])
const fromType = ref('all')
const subActive = ref(0)
const fromTypeFn = (key: any, index: any)=>{
	fromType.value = key;
	subActive.value = index;
	info.value = [];
	getMescroll().resetUpScroll();
}

/************ 类型-start ************/ 
let loading = ref<boolean>(true);//页面加载动画
let infoLoading = ref<boolean>(true);//页面加载动画
const info: Record<string, any> = ref([])
const getSaleMemberFn = (mescroll: any) => {
	infoLoading.value = true;
    getSaleMemberList({
        page: mescroll.num,
        limit: mescroll.size,
		is_send: fromType.value
    }).then((res: any) => {
        let newArr = res.data.data
        //设置列表数据
        if (mescroll.num == 1) {
            info.value = []; //如果是第一页需手动制空列表
			if(fromType.value != '1'){
				getSaleMemberNowListFn(newArr);
			}
        }
        info.value = info.value.concat(newArr);
		infoLoading.value = false;
        mescroll.endSuccess(newArr.length);
    }).catch(() => {
        loading.value = false;
		infoLoading.value = false;
        mescroll.endErr(); // 请求失败, 结束加载
    })
}
const getSaleMemberNowListFn= async(newArr:any)=>{
	loading.value = true;
    const res :any = await getSaleMemberNowList()
	let idArr = newArr.map(el=>el.period_id);
	if(Object.keys(res.data).length &&(idArr.length && idArr.indexOf(res.data.id) == -1 || !idArr.length)){
		let obj = JSON.parse(JSON.stringify(res.data))
		obj.reward_money = obj.total_reward_money;
		obj.period_id = obj.id;
		obj.order_money = obj.total_order_money;
		info.value.unshift(obj);
	}
	loading.value = false;
}
let saleCommission = ref({})
const getSaleMemberCommissionFn=()=>{
    getSaleMemberCommission().then((res:any)=>{
        saleCommission.value = res.data;
    })
}
getSaleMemberCommissionFn()

// 申请提现
const applyCashOut = () => {
	uni.setStorageSync('cashOutAccountType', 'commission')
	redirect({ url: '/app/pages/member/apply_cash_out' })
}

const toDetail = (id: any) => {
    redirect({ url: '/addon/shop_fenxiao/pages/sale_detail', param: {id:id} })
}
</script>
<style lang="scss" scoped>
.wechat {
    background: linear-gradient(to right, var(--primary-color-dark) 40%, var(--primary-color) 90%);
}
.tab-style-1 .tab-left .tab-left-item.class-select::before{
	bottom: 6rpx;
}
</style>